import React, { useContext } from 'react';

import { ReactComponent as Check } from '@/assets/images/auth/Check.svg';
import { ReactComponent as ChevronRight } from '@/assets/images/auth/ChevronRight.svg';
import { setFeedbackFiles } from '@/entities/auth/model/actions';
import { getAccessToken, getFeedbackFiles } from '@/entities/auth/model/selectors';
import { Dropzone } from '@/features/Dropzone';
import { env, urls } from '@/shared/constants';
import { ModalContext } from '@/shared/context/ModalContext';
import { FileWithPreview, Modals, SelectProps } from '@/shared/interfaces';
import { transformArrayIntoObject, validateEmail } from '@/shared/lib';
import { useMetaTag, usePreventRedirect } from '@/shared/lib/hooks';
import { useAppDispatch, useAppSelector } from '@/shared/store';
import { Button, ButtonVariants, FlexWrapper, Input, Modal, Select, Title } from '@/shared/ui';
import axios from 'axios';
import { Router } from 'next/router';
import { useWindowSize } from 'usehooks-ts';

import cs from './Feedback.module.scss';

const sorts = transformArrayIntoObject(['Техническая поддержка', 'Предложения и пожелания', 'Другое']);
export const Feedback = () => {
  const dispatch = useAppDispatch();
  const [sort, setSort] = React.useState<SelectProps | undefined>();
  const [email, setEmail] = React.useState<string>('');
  const [message, setMessage] = React.useState<string>('');
  const [isChoosing, setIsChoosing] = React.useState<boolean>(false);
  const { openModal, setData, data } = useContext(ModalContext);
  const files = useAppSelector(getFeedbackFiles);
  const { width } = useWindowSize();
  const [isNotCorrectEmailShown, setIsNotCorrectEmailShown] = React.useState<boolean>(false);

  React.useEffect(() => {
    if (typeof localStorage === 'undefined') {
      return;
    }
    const emailFromLocalStorage = localStorage.getItem('authEmail');

    if (!emailFromLocalStorage) {
      return;
    }

    setEmail(() => emailFromLocalStorage);
  }, []);

  const [redirectUrl, setRedirectUrl] = React.useState<string | null>(null);
  const accessToken = useAppSelector(getAccessToken);

  const handleSendMessage = async () => {
    const formData = new FormData();
    files?.forEach((file: FileWithPreview) => {
      formData.append('files', {
        uri: file.preview,
        type: file.type,
        name: file.name,
      } as unknown as Blob);
    });
    formData.append('theme', (sort?.title || '').trim());
    formData.append('email', email.trim());
    formData.append('message', message);
    try {
      const response = await axios.post(`${env.apiUrl}/user/send-feedback-unauth`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: `Bearer ${accessToken}`,
        },
      });
      if (response.status === 201) {
        openModal(Modals.MessageSendModal);
      }
    } catch (error: any) {
      throw new Error(error.message);
    }
  };

  React.useEffect(() => {
    Router.events.on('routeChangeStart', setRedirectUrl);
  }, [openModal]);
  const isFull = email.length > 0 && message.length > 0 && sort?.title.length && sort?.title.length > 0;
  React.useEffect(() => {
    setData(() => ({
      isFull,
      handleSendMessage,
      email,
      sort,
      message,
      fromProfile: true,
      url: redirectUrl,
    }));
  }, [redirectUrl, email, sort, message]);

  const handleOpen = () => {
    openModal(Modals.ConfirmModal);
  };

  const onDrop = (files?: FileWithPreview[]) => {
    if (!files) {
      return;
    }
    dispatch(setFeedbackFiles(files));
  };

  usePreventRedirect(data?.sort?.title.length || data?.message?.length, handleOpen);
  useMetaTag(isChoosing && width < 1024, '#999999');
  return (
    <>
      <Modal isMobile isOpen={isChoosing} onCloseClick={() => setIsChoosing(false)}>
        <Title className={cs.title} size="modal-size">
          Тема
        </Title>
        <div className={cs.chooseCont}>
          {sorts.map((item, index) => (
            <span
              className={index !== sorts.length - 1 ? cs.chooseItem : cs.chooseItemWithoutBorder}
              key={item?.id}
              onClick={() => {
                setSort(item);
                setTimeout(() => {
                  setIsChoosing(false);
                }, 50);
              }}
            >
              <>
                {item.title}
                {item.id.toString() === sort?.id.toString() && (
                  <div className={cs.check}>
                    <Check />
                  </div>
                )}
              </>
            </span>
          ))}
        </div>
      </Modal>
      <span className={cs.text}>
        Быстреe ответим в{' '}
        <Button
          data-testid="link-telegram_support"
          href={urls.telegramSupport}
          link
          target="_blank"
          variant={ButtonVariants.Link}
        >
          Telegram
        </Button>
      </span>
      <div className={cs.inputs}>
        <div className={cs.twoInputs}>
          <div className={cs.sort_container}>
            <Select
              className={cs.sort}
              config={{ title: sort?.title || '', values: sorts }}
              isBig
              isFullWidth
              isHover={false}
              onSelect={setSort}
              selected={sorts.filter((item) => item.id === sort?.id)}
              withPlaceholder="Выберите тему"
            />
          </div>
          {width < 768 && (
            <FlexWrapper>
              <div style={{ position: 'relative', zIndex: '1', marginBottom: '16px' }}>
                <Input
                  data-testid="input-topic"
                  disabled={(sort?.title.length || 0) > 0}
                  isFeedback
                  onTouchStart={() => {
                    setIsChoosing(true);
                  }}
                  placeholder="Выберите тему"
                  value={sort?.title}
                />
                <Button
                  className={cs.chevronLeft}
                  data-testid="button-choose"
                  onClick={() => {
                    setIsChoosing(true);
                  }}
                >
                  <ChevronRight />
                </Button>
              </div>
            </FlexWrapper>
          )}
          <FlexWrapper className={cs.input}>
            <Input
              data-testid="input-email"
              isClose={email.length > 0}
              isEmailField
              isNotAccepted={isNotCorrectEmailShown && email.length !== 0}
              isNotAcceptedText="Неверный формат"
              onBlur={() => {
                !validateEmail(email) && setIsNotCorrectEmailShown(true);
              }}
              onChange={(e: { target: { value: React.SetStateAction<string> } }) => {
                setEmail(e.target.value);
                setIsNotCorrectEmailShown(false);
              }}
              onClear={() => setEmail('')}
              placeholder="Почта"
              value={email || ''}
            />
          </FlexWrapper>
        </div>
        <FlexWrapper isModalWidth>
          <div style={{ position: 'relative', width: '100%' }}>
            <textarea
              className={cs.textarea}
              onChange={(e) => setMessage(e.target.value)}
              placeholder="Сообщение"
              value={message}
            ></textarea>
          </div>
        </FlexWrapper>
        <Dropzone handleDrop={onDrop} isLoading={false} />
        <FlexWrapper isCenter>
          <Button
            className={cs.btn}
            data-testid="button-send_message"
            disabled={!sort || !email || !message || isNotCorrectEmailShown}
            onClick={handleSendMessage}
            variant={ButtonVariants.Primary}
          >
            Отправить
          </Button>
        </FlexWrapper>
      </div>
    </>
  );
};
